package cn.iocoder.yudao.module.book.service.book;

import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import org.springframework.validation.annotation.Validated;

import cn.iocoder.yudao.module.book.controller.admin.book.vo.*;
import cn.iocoder.yudao.module.book.dal.dataobject.book.BookDO;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;

import cn.iocoder.yudao.module.book.dal.mysql.book.BookMapper;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.book.enums.ErrorCodeConstants.*;

/**
 * 图书 Service 实现类
 *
 *
 */
@Service
@Validated
public class BookServiceImpl implements BookService {

    @Resource
    private BookMapper Mapper;

    @Override
    public Long create(BookSaveReqVO createReqVO) {
        // 插入
        BookDO bookDO  = BeanUtils.toBean(createReqVO, BookDO.class);
        Mapper.insert(bookDO);
        // 返回
        return bookDO.getId();
    }

    @Override
    public void update(BookSaveReqVO updateReqVO) {
        // 校验存在
        validateExists(updateReqVO.getId());
        // 更新
        BookDO updateObj = BeanUtils.toBean(updateReqVO, BookDO.class);
        Mapper.updateById(updateObj);
    }

    @Override
    public void delete(Long id) {
        // 校验存在
        validateExists(id);
        // 删除
        Mapper.deleteById(id);
    }

    private void validateExists(Long id) {
        if (Mapper.selectById(id) == null) {
            throw exception(BOOK_NOT_EXISTS);
        }
    }

    @Override
    public BookDO get(Long id) {
        return Mapper.selectById(id);
    }

    @Override
    public PageResult<BookDO> getPage(BookPageReqVO pageReqVO) {
        return Mapper.selectPage(pageReqVO);
    }

}